package io.renren.modules.ProjectControl.Service.ExeCommandService;

import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ExeServiceP3_1Impl implements ExeServiceP3_1 {
    public  void Start(String Command) throws IOException, InterruptedException {

        Runtime runtime = Runtime.getRuntime();
        runtime.exec(Command);

    }

    @Override
    public String Stop(String Command) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        runtime.exec(Command);
        return "StopP3-1";
    }

    @SneakyThrows
    @Override
    public String Status() throws IOException {
        Runtime runtime=Runtime.getRuntime();

        Process process = runtime.exec("cmd /c netstat -ano | findstr \"8088\"");

        List<String> read = read(process.getInputStream(), "UTF-8");
        if(read.size() == 0){
            System.out.println("找不到该端口的进程");
        }else{
            for (String string : read) {
                System.out.println(string);
            }
            System.out.println("找到"+read.size()/2+"个进程");

        }
        Set<Integer> pids = new HashSet<>();
        for (String line : read) {
            int offset = line.lastIndexOf(" ");
            String spid = line.substring(offset);
            spid = spid.replaceAll(" ", "");
            int pid = 0;
            try {
                pid = Integer.parseInt(spid);
            } catch (NumberFormatException e) {
                System.out.println("获取的进程号错误:" + spid);
            }
            pids.add(pid);
        }
        System.out.println(pids);


        return pids.toString();
    }


    private List<String> read(InputStream in, String charset) throws IOException{
        List<String> data = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset));
        String line;
        while((line = reader.readLine()) != null){
            System.out.println(line);
            data.add(line);
        }
        reader.close();
        return data;
    }
}
